import React, { useEffect, useRef, useState } from 'react';
import './ChatBox.css';
import { useLocation } from 'react-router-dom';
import ReactMarkdown from 'react-markdown'
// 替换为你的 WebSocket 地址

export default function ChatBox() {
  const location = useLocation();
  const news = location.state;
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isSentOnce, setIsSentOnce] = useState(false);
  const msgEndRef = useRef(null);
  const hasFetched = useRef(false);
  const ws = useRef(null);

  
  //当前正在生成的消息
  const [currentStreamingText, setCurrentStreamingText] = useState('');
  useEffect(() => {
    ws.current = new WebSocket('ws://localhost:8001/ws');
    
    ws.current.onopen = (event) => {
      console.log('WebSocket is open now.');
      const message={"id":localStorage.getItem("userId"),"type":"login"};
      ws.current.send(JSON.stringify(message));
      const query={"id":localStorage.getItem("userId"),"question":news,"type":"summary"};
      ws.current.send((JSON.stringify(query)));
      
    };
    ws.current.onmessage = (e) => {
      const chunk = e.data;
      if (chunk === '__END__') {
        setMessages((prev) => [...prev, { from: 'server', text: currentStreamingText }]);
        setCurrentStreamingText('');
      } else {
        setCurrentStreamingText((prev) => prev + chunk);
      }
    };
  

    ws.current.onclose = () => {
      console.log('WebSocket is closed now.');
    };

    ws.current.onerror = (error) => {
      console.error('WebSocket error: ', error);
    };

    // 在组件卸载时关闭 WebSocket 连接
    return () => {
      ws.current.close();
    };
    
  }, []);

  useEffect(() => {
    msgEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const sendMessage = () => {
    if (!input.trim()) return;
    if (currentStreamingText) {
      setMessages((prev) => [...prev, { from: 'server', text: currentStreamingText }]);
      setCurrentStreamingText('');
    }
    setMessages((prev) => [...prev, { from: 'user', text: input }]);
    const data={"question":input,"type":"chat","id":localStorage.getItem("userId")}
    if (ws.current.readyState === WebSocket.OPEN) {
      ws.current.send(JSON.stringify(data));
  } else {
    console.log('WebSocket connection is not open.');
  }
    setInput('');
    setIsSentOnce(true);
  };

  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map((msg, idx) => (
          <div key={idx} className={`msg ${msg.from}`}>
            <ReactMarkdown>{msg.text}</ReactMarkdown>
          </div>
        ))}
        {currentStreamingText && (
          <div className="msg server">
            <ReactMarkdown>{currentStreamingText}</ReactMarkdown>
          </div>
        )}
        <div ref={msgEndRef} />
      </div>

      <div className={`input-area ${isSentOnce ? 'bottom' : 'center'}`}>
        <input
          className='search-input'
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
          placeholder="输入消息..."
        />
        <button className='search-button' onClick={sendMessage}>🔍</button>
        
      </div>
    </div>
  );
}

